package com.walkingfiles.registry

import com.walkingfiles.registry.Document
import com.walkingfiles.registry.Area
import com.walkingfiles.registry.DocumentState
import com.walkingfiles.alfresco.Utils
import com.walkingfiles.pubsub.PubSub
import org.springframework.dao.DataIntegrityViolationException

import grails.plugin.springsecurity.annotation.Secured
import grails.plugin.springsecurity.SpringSecurityService

@Secured(['ROLE_USER'])
class DocumentController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

	def springSecurityService

    def index() {
        redirect(action: "list", params: params)
    }

    def list() {	
		def listParams = [
			max: Math.min(params.max ? params.int('max') : 10, 100)
		]
		if (!params.sort) {
			listParams.sort = "modifiedDate"
			listParams.order = "desc"
		} else {
			listParams.sort = params.sort
			listParams.order = params.order
		}
		def query = Document.where {
			currentArea == Area.findByName(session.currentAreaName)
			transfer == null
		}
		if (params.number) {
			query = query.where {
				number =~ String.format('%%%1s%%', params.number)
			}
		}
		if (params.date_from != null) {
			query = query.where {
				date >= params.date_from
			}
		}
		if (params.date_to != null) {
			query = query.where {
				date <= params.date_to
			}
		}
        [documentInstanceList: query.list(listParams), 
		 documentInstanceTotal: query.count(),
		 params: params]
    }

    def create() {
        [documentInstance: new Document(params)]
    }

    def save() {
		def documentInstance = new Document(params)
		documentInstance.currentArea = Area.findByName(session.currentAreaName)
		documentInstance.state = DocumentState.findByName('N')
		documentInstance.modifiedDate = new Date()
		
		if (!documentInstance.save(flush: true)) {
			render(view: "create", model: [documentInstance: documentInstance])
			return
		}
		def username = authenticatedUser.username
		LogItem.documentCreated(documentInstance, username)
        PubSub.pub('documentCreated', 'alalal')

		flash.message = message(code: 'default.created.message', args: [message(code: 'document.label', default: 'Document'), documentInstance.id])
		redirect(action: "show", id: documentInstance.id)
    }

    def show() {
        def documentInstance = Document.get(params.id)
        if (!documentInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'document.label', default: 'Document'), params.id])
            redirect(action: "list")
            return
        }

        println '!"#!"#!"#'

        [documentInstance: documentInstance]
    }

    def edit() {
        def documentInstance = Document.get(params.id)
        if (!documentInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'document.label', default: 'Document'), params.id])
            redirect(action: "list")
            return
        }

        [documentInstance: documentInstance]
    }

    def update() {
		
        def documentInstance = Document.get(params.id)
        if (!documentInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'document.label', default: 'Document'), params.id])
            redirect(action: "list")
            return
        }

        if (params.version) {
            def version = params.version.toLong()
            if (documentInstance.version > version) {
                documentInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                          [message(code: 'document.label', default: 'Document')] as Object[],
                          "Another user has updated this Document while you were editing")
                render(view: "edit", model: [documentInstance: documentInstance])
                return
            }
        }

        documentInstance.properties = params

        if (!documentInstance.save(flush: true)) {
            render(view: "edit", model: [documentInstance: documentInstance])
            return
        }

		flash.message = message(code: 'default.updated.message', args: [message(code: 'document.label', default: 'Document'), documentInstance.id])
        redirect(action: "show", id: documentInstance.id)
    }

    def delete() {
        def documentInstance = Document.get(params.id)
        if (!documentInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'document.label', default: 'Document'), params.id])
            redirect(action: "list")
            return
        }

        try {
            documentInstance.delete(flush: true)
			flash.message = message(code: 'default.deleted.message', args: [message(code: 'document.label', default: 'Document'), params.id])
            redirect(action: "list")
        }
        catch (DataIntegrityViolationException e) {
			flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'document.label', default: 'Document'), params.id])
            redirect(action: "show", id: params.id)
        }
    }

	def addToOutbox() {
		def documentInstance = Document.get(params.id)
		println documentInstance.outbox
		documentInstance.outbox = true
		documentInstance.save(flush:true)
		println documentInstance
		println documentInstance.outbox
		render remoteLink(action:'removeFromOutbox', id: params.id, update:'outboxDiv'+params.id){'Remove'}
	}

	def removeFromOutbox() {
	    def documentInstance = Document.get(params.id)
		println documentInstance.outbox
		documentInstance.outbox = false
		documentInstance.save(flush:true)
		println documentInstance
		println documentInstance.outbox
		render remoteLink(action:'addToOutbox', id: params.id, update:'outboxDiv'+params.id){'Add'}
	}
    
    def showLog() {
        def documentInstance = Document.get(params.id)
        if (!documentInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'document.label', default: 'Document'), params.id])
            redirect(action: "list")
            return
        }
        return [documentInstance: documentInstance]
    }

    def showFiles() {
        def documentInstance = Document.get(params.id)
        if (!documentInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'document.label', default: 'Document'), params.id])
            redirect(action: "list")
            return
        }
        def documentRoot = new Utils(grailsApplication.config.alfresco)
                                    .rootPathForDocument(documentInstance)
                
        [documentInstance: documentInstance, documentRoot: documentRoot]
    }

}
